package cc.aiee.wxpay.config;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.impl.client.CloseableHttpClient;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

import cn.hutool.core.util.StrUtil;

public class WxPayScoreConfigKit {

	private static Map<String, CloseableHttpClient> HCT_MAP = new ConcurrentHashMap<String, CloseableHttpClient>();

	public static CloseableHttpClient getHttpClientCache(WxPayScoreConfig config) {
		String appId = config.getAppId();
		if (HCT_MAP.containsKey(appId)) {
			return HCT_MAP.get(appId);
		}
		CloseableHttpClient httpClient = getHttpClient(config);
		if (httpClient == null) {
			throw new IllegalArgumentException(StrUtil.format("WxPayScoreConfig NULL,appid:{}", appId));
		}
		HCT_MAP.put(appId, httpClient);
		return httpClient;
	}

	public static boolean setHttpClientCache(WxPayScoreConfig config) {
		CloseableHttpClient httpClient = getHttpClient(config);
		HCT_MAP.put(config.getAppId(), httpClient);
		return true;
	}

	public static CloseableHttpClient getHttpClient(WxPayScoreConfig config) {
		try {
			String privateKey = config.getPrivateKey();

			String mchId = config.getMchId();
			String mchSerialNo = config.getMchSerialNo();
			String apiV3Key = config.getApiV3Key();

			// 加载商户私钥（privateKey：私钥字符串）
			PrivateKey merchantPrivateKey = PemUtil
					.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));

			// 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3秘钥）
			AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
					new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),
					apiV3Key.getBytes("utf-8"));

			// 初始化httpClient
			CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
					.withMerchant(mchId, mchSerialNo, merchantPrivateKey)
					.withValidator(new WechatPay2Validator(verifier)).build();

			return httpClient;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
